﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace RoadTest
{
    class SimpleTrafficLightStrategy : iTrafficLightStrategy
    {
        private Thread strategyThread;
        private Lane[] lanes;

        public void start(Lane[] lanes)
        {
            this.lanes = lanes;
            strategyThread = new Thread(handleTraffic);
            strategyThread.Start();
        }

        public void stop()
        {
            strategyThread.Abort();
        }

        private void handleTraffic()
        {
            try
            {
                while (true)
                {
                    foreach (Lane gl in lanes)
                    {
                        Thread.Sleep(2000);
                        Lane lastSet = gl;
                        if (gl.hasTrafficLight())
                        {
                            TrafficLight t = gl.trafficLight;
                            t.Dispatcher.Invoke(
                            new Action(delegate()
                            {
                                t.SetValue(TrafficLight.statusProperty, TrafficLightStatus.GREEN);
                            }));
                        }
                        foreach (Lane rl in lanes)
                        {
                            if (rl.hasTrafficLight() && rl.GetHashCode() != lastSet.GetHashCode())
                            {
                                TrafficLight t = rl.trafficLight;
                                if (t != null)
                                {
                                    t.Dispatcher.Invoke(
                                    new Action(delegate()
                                    {
                                        t.SetValue(TrafficLight.statusProperty, TrafficLightStatus.RED);
                                    }));
                                }
                            }
                        }
                    }
                }
            }
            catch (ThreadAbortException e)
            {
                Trace.WriteLine("Thread was aborted by: " + e.GetType());
                return;
            }
        }
    }
}
